"""
adapted from django.
Decorators for views based on HTTP headers.
"""

from hashlib import md5
from bodhi.utils.http import patch_cache_control

class ETagFilter:
    order = 10

    def __init__(self, calculate_etag=True):
        if calculate_etag is True:
            calculate_etag = lambda req: True
        elif calculate_etag is False:
            calculate_etag = lambda req: False
        self.calculate_etag = calculate_etag

    def __call__(self, view, next):
        next()

        request = view.request
        response = view.response
        etag = response.get_header('ETag')
        if etag:
            if request.environ.get('HTTP_IF_NONE_MATCH') == etag:
                response.status_code = 304
        elif request.method == 'GET' and response.status_code == 200 and self.calculate_etag(request):
            etag = '"' + md5(response.content).hexdigest() + '"'

            if request.environ.get('HTTP_IF_NONE_MATCH') == etag:
                response.status_code = 304
            else:
                response.set_header('ETag', etag)
        # content, Content-Length and Content-Type will be cleared in 
        # fix_response if status_code == 304.


class NeverCacheFilter:
    order = -10

    def __call__(self, view, next):
        next()
        patch_cache_control(view.response, max_age='0', no_cache=True, no_store=True)
